package org.cainiao.io.netty.other.buffer.composite;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import org.cainiao.io.netty.other.buffer.CommonTest;

import java.nio.ByteBuffer;

/**
 * <br />
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
public class CompositeTest {

    public static void main(String[] args) {
        nio(null, null);
        composite();
        useArray();
    }

    private static void useArray() {
        CompositeByteBuf compBuf = Unpooled.compositeBuffer();
        int length = compBuf.readableBytes();
        byte[] array = new byte[length];
        compBuf.getBytes(compBuf.readerIndex(), array);
        CommonTest.handleArray(array, 0, array.length);
    }

    private static void composite() {
        CompositeByteBuf messageBuf = Unpooled.compositeBuffer();
        ByteBuf headerBuf = null; // can be backing or direct
        ByteBuf bodyBuf = null; // can be backing or direct
        messageBuf.addComponents(headerBuf, bodyBuf);
        // .....
        messageBuf.removeComponent(0); // remove the header
        for (ByteBuf buf : messageBuf) {
            System.out.println(buf.toString());
        }
    }

    private static void nio(ByteBuffer header, ByteBuffer body) {
        // Use an array to hold the message parts
        ByteBuffer[] message = new ByteBuffer[]{header, body};
        // Create a new ByteBuffer and use copy to merge the header and body
        ByteBuffer message2 = ByteBuffer.allocate(header.remaining() + body.remaining());
        message2.put(header);
        message2.put(body);
        message2.flip();
    }

}
